package
{
	import flash.system.Capabilities;
	import flash.utils.setTimeout;
	import flash.utils.clearTimeout;
	import flash.display.Sprite;
	import flash.text.TextField;

	public class Toast extends Sprite
	{
		private static var _main:Toast;

		public static function get main():Toast
		{
			if (_main == null)
				_main = new Toast();
			return _main;
		}
		private static var txt:TextField;
		private static var bg:Sprite;
		private static var bgColor:uint=0x333333;

		private static var _stageWidth:int;
		private static var _stageHeight:int;
		private static function get stageW():int
		{
			if(_stageWidth>0)
				return _stageWidth;
			if (main.stage)
			{
				_stageWidth = main.stage.stageWidth/main.stage.scaleX;
				return _stageWidth;
			}
			_stageWidth = Capabilities.screenResolutionX;
			return _stageWidth;
		}

		private static function get stageH():int
		{
			if(_stageHeight>0)
				return _stageHeight;
			if (main.stage)
			{
				_stageHeight = main.stage.stageHeight/main.stage.scaleY;
				return _stageHeight;
			}
			_stageHeight = Capabilities.screenResolutionY;
			return _stageHeight;
		}


		public function Toast(fontColor:uint=0xffffff,_bgColor:uint=0x333333,_stageW:int=0,_stageH:int=0)
		{
			_main = this;
			_stageWidth = _stageW;
			_stageHeight = _stageH;
			bgColor = _bgColor;
			if (txt == null)
				txt = ViewSet.makeTxtLine("", 30, fontColor);
			if (bg == null)
				bg = new Sprite();
			bg.addChild(txt);
			addChild(bg);
			visible = false;
		}

		private static var timeoutid:uint;
		public static var msg:String = "";

		public static function show(s:String, time:int = 1500):void
		{
			if (main.stage == null)
				return;
			CONFIG::debugging
			{
				logs.adds(s);
			}
			msg = s;
			main.stage.addChild(main);
			main.graphics.clear();
			TweenLite.killTweensOf(bg,true);
			main.visible = true;
			txt.text = s;
			txt.x = -txt.width / 2;
			main.x = stageW / 2;
			//main.y = stageH * .75;
			main.y = stageH * .5;
			//CONFIG::debugging { main.y = stageH*.5; }
			bg.alpha = 1.0;
			with (bg.graphics)
			{
				clear();
				beginFill(bgColor);
				drawRoundRect(txt.x - txt.height / 2, txt.y - txt.height / 2, txt.width + txt.height, txt.height * 2, txt.height, txt.height);
				endFill();
			}
			clearTimeout(timeoutid);
			if (time > 0){
				TweenLite.from(bg, .3, {y: stageH});
				timeoutid = setTimeout(fadeout, time);
			}else{
				with(main.graphics)
				{
					beginFill(0x0,0.4);
					drawRect(-stageW,-stageH,stageW*2,stageH*2);
					endFill();
				}
			}
		}

		private static function fadeout():void
		{
			clearTimeout(timeoutid);
			TweenLite.killTweensOf(bg);
			TweenLite.to(bg, .3, {alpha: 0, onComplete: hide});
		}

		public static function hide():void
		{
			TweenLite.killTweensOf(bg);
			clearTimeout(timeoutid);
			main.visible = false;
			main.graphics.clear();
		}
	}
}
